package com.qdlc.p2p.manage.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ModelDriven;
import com.qd.p2p.adapter.AdaptedRequestHandleService;
import com.qd.p2p.adapter.param.QueryP2PBusinessParameter;
import com.qd.p2p.adapter.response.QueryP2PBusinessResponse;
import com.qd.p2p.adapter.response.QueryP2PBusinessResponse.Order;
import com.qd.p2p.baofoo.enums.P2pBizType;
import com.qdlc.p2p.biz.service.BorrowTenderService;
import com.qdlc.p2p.biz.service.TppService;
import com.qdlc.p2p.biz.service.TppTradeService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.task.ConcurrentUtil;
import com.qdlc.p2p.biz.tpp.TppBaseInterface;
import com.qdlc.p2p.biz.tpp.TppServiceFactory;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.BorrowTender;
import com.qdlc.p2p.dal.dto.Tpp;
import com.qdlc.p2p.dal.dto.TppTradeLog;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.AccountFlowModel;
import com.qdlc.p2p.dal.model.AccountModel;
import com.qdlc.p2p.dal.model.TppAccountModel;
import com.qdlc.p2p.dal.model.TppModel;
import com.qdlc.p2p.dal.util.SystemConfigs;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 用户托管资金差额管理
 *
 * @author ygw
 * @version 2.0
 * @since 2015-11-22
 */
public class ManageTppQueryAccountDetailsAction extends BaseAction<AccountModel> implements
        ModelDriven<AccountModel> {
    @Resource
    private UserService userService;

    @Resource
    private TppService tppService;

    @Resource
    private BorrowTenderService borrowTenderService;

    @Resource
    private TppTradeService tppTradeService;
    
    @Resource
    protected AdaptedRequestHandleService aRHSerivce;

    private Map<String, Object> map = new HashMap<String, Object>();

    /**
     * 托管流水查询页面
     *
     * @return
     * @throws Exception
     */
    @Action("/modules/tpp/tppMerchantLog/" + Constant.TPP_PACKAGE + "/queryAccountDetails")
    public String tppQueryAccountDetails() throws Exception {
        return "tppQueryAccountDetails";
    }

    /**
     * 第三方业务/资金流水查询页面
     *
     * @return
     * @throws Exception
     */
    @Action("/modules/tpp/tppMerchantLog/" + Constant.TPP_PACKAGE + "/doQueryAccountDetails")
    public void dopQueryAccountDetails() throws Exception {
        Map data = new HashMap<String, Object>();
        data.put("hasError", false);

        String searchName = model.getSearchName();
        if(!"baofoo".equals(SystemConfigHelper.getSystemConfig(Nid.TPP_NAME).getValue()) && StringUtil.isEmpty(searchName))
        {
            data.put("hasError", true);
            data.put("message", "用户ID或用户名不能为空");
            printJson(getStringOfJpaObj(data));
            return;
        }
        
        String startTime = model.getStartTime();
        String endTime = model.getEndTime();
        if(StringUtil.isEmpty(startTime)) {
            data.put("hasError", true);
            data.put("message", "开始时间不能为空");
            printJson(getStringOfJpaObj(data));
            return;
        }

        if(StringUtil.isEmpty(endTime)) {
            data.put("hasError", true);
            data.put("message", "结束时间不能为空");
            printJson(getStringOfJpaObj(data));
            return;
        }
        
        String accountType = model.getAccountType();
        String p2pBizType = P2pBizType.USER.getType()+"";
        User user = null;
		if (!StringUtil.isBlank(searchName)) {
        	user = userService.getUserByUserName(searchName);
            if(user == null){
            	try{
                	user = userService.getUserById(Long.valueOf(searchName));
                }catch(Exception e){
                	
                }
            }
            if(user == null)
            {
                data.put("hasError", true);
                data.put("message", "用户不存在");
                printJson(getStringOfJpaObj(data));
                return;
            }
        } else if ("baofoo".equals(SystemConfigHelper.getSystemConfig(Nid.TPP_NAME).getValue()) && p2pBizType.equals(accountType) && StringUtil.isBlank(searchName)) {
        	data.put("hasError", true);
            data.put("message", "请输入用户名");
            printJson(getStringOfJpaObj(data));
            return;
        }
		
        if ("baofoo".equals(SystemConfigHelper.getSystemConfig(Nid.TPP_NAME).getValue())) {// 查询宝付托管账户收支明细
            QueryP2PBusinessParameter parameter = new QueryP2PBusinessParameter();
            if (p2pBizType.equals(accountType) && user != null) {
            	parameter.setOrderId(user.getTppUserCustId());
            }
    		parameter.setType(Integer.valueOf(accountType));

    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		long start = 0L;
    		long end = 0L;
    		start = sdf.parse(startTime).getTime();
    		end = sdf.parse(endTime).getTime();
    		if (!p2pBizType.equals(accountType)) {
    			parameter.setStartTime(start);
    			parameter.setEndTime(end);
            }
    		QueryP2PBusinessResponse bfAccountDetails = aRHSerivce.queryP2PBusiness(parameter);
            if(null==bfAccountDetails){
            	{
                    data.put("hasError", true);
                    data.put("message", SystemConfigHelper.getSystemConfig(Nid.TPP_NAME).getValue()+"提交异常,详情查看日志 ");
                    printJson(getStringOfJpaObj(data));
                    return;
                }
            }
            
            List<AccountFlowModel> rowsList = new ArrayList<AccountFlowModel>();
            
            List<Order> accountDetailsList = bfAccountDetails.getResult();
            for (Order accountDetail : accountDetailsList) {
            	AccountFlowModel accountFlow = new AccountFlowModel();
            	accountFlow.setAccountType(accountType);
            	accountFlow.setOrderId(accountDetail.getOrderId());
            	accountFlow.setChangeAmount(accountDetail.getSuccAmount()+"");
            	accountFlow.setFee(accountDetail.getFee());
            	accountFlow.setBaofooFee(accountDetail.getBaofooFee());
            	if (accountDetail.getFeeTakenOn() != null) {
            		accountFlow.setFeeTakenOn(accountDetail.getFeeTakenOn().intValue());
            	} else {
            		accountFlow.setFeeTakenOn(9);// 未知状态
            	}
            	accountFlow.setState(accountDetail.getState());
            	if (accountDetail.getSuccTime() != null) {
            		accountFlow.setTime(accountDetail.getSuccTime());	
            	}
            	accountFlow.setUserId(accountDetail.getUserId());
            	accountFlow.setAccountName(accountDetail.getAccountName());
            	accountFlow.setCreateTime(accountDetail.getCreateTime());
            	accountFlow.setEmail(accountDetail.getEmail());
    			rowsList.add(accountFlow);
    		}
            
            data.put("rows", rowsList);
            data.put("total", rowsList.size());
            printJson(getStringOfJpaObj(data));
            
        } else {// 查询新浪托管账户收支明细
            TppModel detailsTppModel = new TppModel();
            detailsTppModel.setUser(user);
            detailsTppModel.setStartTime(DateUtil.dateStr3( DateUtil.valueOf(model.getStartTime())));
            detailsTppModel.setEndTime(DateUtil.dateStr3(DateUtil.valueOf(model.getEndTime())));
            detailsTppModel.setPage(model.getPage());
            detailsTppModel.setRows(model.getRows());
            detailsTppModel.setExtendParam(""); // svp_trade_type^bonus – 只返回收益;svp_trade_type^in_out – 只返回收入和支出
            TppBaseInterface detailsTppService = TppServiceFactory.newIntance();
            // 托管账户收支明细
            TppAccountModel accountDetails = (TppAccountModel) detailsTppService.tppQueryAccountDetailsPagination(detailsTppModel);
            //accountDetails.getDetail_list();
            if(null==accountDetails){
            	{
                    data.put("hasError", true);
                    data.put("message", SystemConfigHelper.getSystemConfig(Nid.TPP_NAME).getValue()+"提交异常,详情查看日志 ");
                    printJson(getStringOfJpaObj(data));
                    return;
                }
            }
            List<AccountFlowModel> rowsList = new ArrayList<AccountFlowModel>();
            
            String[] accountDetailsList=  accountDetails.getDetail_list().split("\\|");
            for (String accountDetail : accountDetailsList) {
            	AccountFlowModel accountFlow = new AccountFlowModel();
            	String[] accountRemark = null;
            	String accountFlag="";
            	if(accountDetail.contains("BONUS")||accountDetail.contains("IN")){
            		accountRemark = accountDetail.split("[+]");
            		accountFlag="+";
            	}
            	if(accountDetail.contains("OUT")){
            		accountRemark = accountDetail.split("[-]");
            		accountFlag="-";
            	}
    			String[] remarkAndTime = accountRemark[0].split("\\^");
    			accountFlow.setRemark(remarkAndTime[0]);
    			accountFlow.setTime(formatTime(remarkAndTime[1]));
    			String[] changeAmountAndAccountBalance = accountRemark[1].split("\\^");
    			accountFlow.setChangeAmount(accountFlag+changeAmountAndAccountBalance[1]);
    			accountFlow.setAccountBalance(changeAmountAndAccountBalance[2]);
    			rowsList.add(accountFlow);
    		}
            data.put("rows", rowsList);
            data.put("total", accountDetails.getTotal_item());
            data.put("pageNums", accountDetails.getPage_no());
            data.put("pageSize", accountDetails.getPage_size());
            
            printJson(getStringOfJpaObj(data));
        }
    }


    /**
     * 托管退款页面
     *
     * @return
     * @throws Exception
     */
    @Action("/modules/tpp/tppMerchantLog/"+ Constant.TPP_PACKAGE +"/sinaRefundPage")
    public String sinaRefundPage() throws Exception {
        return "sinaRefundPage";
    }

    /**
     * 退款列表
     * @return
     * @throws Exception
     */
    @Action("/modules/tpp/tppMerchantLog/"+ Constant.TPP_PACKAGE +"/sinaRefundList")
    public void sinaRefundList() throws Exception {
        String subOrdId = model.getSearchName();
        PageDataList<TppModel> list = tppService.findRefundList(model);
        map.put("total", list.getPage().getTotal());
        map.put("rows", list.getList());
        printJson(getStringOfJpaObj(map));
    }

    /**
     * 新浪退款
     *
     * @return
     * @throws Exception
     */
    @Action("/modules/tpp/tppMerchantLog/" + Constant.TPP_PACKAGE + "/doSinaRefund")
    public void doSinaRefund() throws Exception {
        List<TppModel> taskList = new ArrayList<TppModel>();
        BorrowTender tender = null;
        String serviceType = TppModel.REFUNDBYSUBORDIDN;
        //是否处理本地资金
        if("Y".equals(paramString("isDealLocal")))
            serviceType = TppModel.REFUNDBYSUBORDIDY;
        String subOrdId = model.getSearchName();
        if(StringUtil.isEmpty(subOrdId)) {
            printWebResult("交易订单号不能为空！", false);
            return;
        }

        TppTradeLog tppTradeLog = tppTradeService.find(subOrdId);
        if (null == tppTradeLog) {
            printWebResult("交易订单号不存在！", false);
            return;
        }
        User toUser = UserUtils.getUserByTppCustId(tppTradeLog.getTppUserCustId());
        toUser = (toUser == null ? new User(SystemConfigs.ADMIN_ID) : toUser);
        User user = UserUtils.getUserByTppCustId(tppTradeLog.getToTppUserCustId());
        double money = tppTradeLog.getMoney();
        //投标退款不处理本地资金
        if ("tender".equals(tppTradeLog.getServiceType())) {
            serviceType = TppModel.REFUNDBYSUBORDIDN;
            tender = borrowTenderService.getTenderByBillNo(subOrdId);
        }
        //user原先交易的收款人；toUser原先交易的付款人
        Tpp refundTpp = new Tpp(serviceType, TppModel.TPP_REFUND, user, toUser, money, tender);
        refundTpp.setSubOrdId(subOrdId);
        taskList.add(TppModel.instance(refundTpp));
        // 请求第三方接口，进行资金退款
        if ("baofoo".equals(SystemConfigHelper.getSystemConfig(Nid.TPP_NAME).getValue())) {// 宝付
        } else {// 新浪
        	ConcurrentUtil.tppTask(taskList);
        }
        printWebResult("退款申请已提交！", true);
    }

    public String formatTime(String time){
    	return time.substring(0, 4)+"-"+time.substring(4, 6)+"-"+ time.substring(6,8)+" "+time.substring(8,10)+":"+time.substring(10,12)+":"+time.substring(12,14);
    }
}
